<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use app\common\controller\AdminBaseController;

class Index extends AdminBaseController
{
    public function index()
    {
    	
    	return $this->fetch();
    }
	
	//余额异常
	public function balance_trace(){
		$map['truncate(m.balance,2)'] = ['exp',"<> truncate(a.balance1,2)"];
		$map1['status_tinyint'] = 1;
		if(request()->isPost()){ 	
		 	$param = input('post.');
			if($param['name']){
				$map['m.agent_name'] = ['like', '%'.$param['name'].'%'];
			}
		}
		//$map1['add_time']=['<=',date('Y-m-d',time())];
		$ye=db('log_agent_charge')->where($map1)->field('agent_id,status_tinyint,order_type,sum(balance) as balance1')->group('agent_id')->buildSql();
    	$list=db('info_agent')->alias('m')
    	->join($ye.'a','m.id=a.agent_id','INNER')->where($map)
    	->field('m.*,truncate(a.balance1,2) as balance1')->paginate(20);
		$this->assign('empty','<span class="empty">没有数据</span>');
        return $this->fetch('balance_trace', ['list' => $list]);
	}
		//鼓励金购买记录导出
    public function cz_dc(){
		$where['order_type']=["in",[5,8,9]];
		if(input("begin_time")&&input("end_time")){
			$where['add_time']=["between",[input("begin_time"),input("end_time")]];
		}elseif(input("begin_time")){
			$where['add_time']=['>=',input("begin_time")];
		}elseif(input("end_time")){
			$where['add_time']=['<=',input("end_time")];
		}
    	$list=db("log_paylog_copy")->where($where)->select();
		$str ="购买类型,编号,购买金额,手续费,实际到账金额,详细,到账鼓励金,交易时间"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$cz_type="会员";
			$type_id='uid';
			if($row['order_type']==5){
				$cz_type="商家";
				$type_id="agent_id";
			}elseif($row['order_type']==9){
				$cz_type="oem";
				$type_id="oem_id";
			}
			$u_id = iconv('utf-8','gbk',$cz_type);
			$mobile = iconv('utf-8','gbk',$row[$type_id].'	');
			$balance = iconv('utf-8','gbk',$row['balance']);
			$sxf = iconv('utf-8','gbk',$row['balance']*0.25/100);
			$dzje=iconv('utf-8','gbk',$row['balance']*99.75/100);
			$message = iconv('utf-8','gbk',$row['message']);
			$balance1 = iconv('utf-8','gbk',$row['balance']); 
			$add_time = iconv('utf-8','gbk',$row['add_time'].'	');
			$str .= $u_id.",".$mobile.",".$balance.",".$sxf.",".$dzje.",".$message.",".$balance1.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='鼓励金购买记录.csv';   //设置文件名 
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	
	/**
	 * 购买记录
	 */
	public function balance_logs(){
		$where['order_type']=["in",[5,8,9]];
		$w1['cash_state']=2;
		if(input("begin_time")&&input("end_time")){
			$where['add_time']=["between",[input("begin_time"),input("end_time")]];
			$w1['create_time']=["between",[input("begin_time"),input("end_time")]];
			$this->assign('begin_time',input("begin_time"));
			$this->assign('end_time',input("end_time"));
		}elseif(input("begin_time")){
			$where['add_time']=['>=',input("begin_time")];
			$w1['create_time']=['>=',input("begin_time")];
			$this->assign('begin_time',input("begin_time"));
		}elseif(input("end_time")){
			$where['add_time']=['<=',input("end_time")];
			$w1['create_time']=['<=',input("end_time")];
			$this->assign('end_time',input("end_time"));
		}
		$total_czs=db("log_paylog_copy")->where($where)->sum('balance');
		$this->assign('czs',$total_czs);
		$user_txs=db("user_withdrawals")->where($w1)->sum("balance");
		$oem_txs=db("oem_withdrawals")->where($w1)->sum("balance");
		$total_txs=$user_txs?$user_txs:0+$oem_txs?$oem_txs:0;
		$this->assign('txs',$total_txs);
		$list=db("log_paylog_copy")->where($where)->paginate(15);
		$this->assign("list",$list);
		
		//会员提现
		$hytx = db("log_user_charge")->where('order_type',1)->sum("balance");
		//商家提现
		$sjtx = db("log_agent_charge")->where('order_type',5)->sum("balance");
		//oem提现
		$oemtx = db("log_oem_charge")->where('order_type',1)->sum("balance");
		$this->assign('txze',$hytx+$sjtx+$oemtx);
		return $this->fetch();
	}
	
    public function welcome(){
	   	$users=db("info_user")->cache(30)->count();
	   	$today_users=db("info_user")->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->whereTime('add_time', 'week')->cache(60)->count();
	   	$month_users=db("info_user")->whereTime('add_time', 'month')->cache(60)->count();
	   	$agents=db("info_agent")->cache(30)->count();
	   	$today_agents=db("info_agent")->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_agents=db("info_agent")->whereTime('add_time', 'week')->cache(60)->count();
	   	$month_agents=db("info_agent")->whereTime('add_time', 'month')->cache(60)->count();
		   
	   	//购买的鼓励金总额-提现金额
		$user_tx=db("log_user_charge")->cache(30)->where('order_type',1)->sum("balance");
		$agent_tx=db("log_agent_charge")->cache(30)->where('order_type',5)->sum("balance");
		$oem_tx=db("log_oem_charge")->cache(30)->where('order_type',1)->sum("balance");
		   
   		$balances=db("log_paylog_copy")->cache(30)->where('order_type','in','5,8,9')->sum("balance");		
	   	$this->assign("balances",$balances+$user_tx+$agent_tx+$oem_tx);
		
	   	$user_scores=db("info_user")->cache(30)->sum("score");
	   	$agent_scores=db("info_agent")->cache(30)->sum("score");
	   	$oem_scores=db("info_oem")->cache(30)->sum("score");
	   	$total_score=$user_scores+$agent_scores+$oem_scores;
	   	$this->assign('total_scores',$total_score);
		   
	   	$user_balance=db("info_user")->cache(30)->sum("balance");
	   	$agent_balance=db("info_agent")->cache(30)->sum("balance");
	   	$oem_balance=db("info_oem")->cache(30)->sum("balance");
	   	$total_balance=$user_balance+$agent_balance+$oem_balance;
	   	$this->assign('total_balance',$total_balance);
		   $wt['type']=['neq',5];
	   	$pts=db("admin_charge")->where($wt)->sum('balance');
		
	   	$today_pts=db("admin_charge")->whereTime('add_time', 'today')->where($wt)->cache(30)->sum("balance");
	   	$month_pts=db("admin_charge")->whereTime('add_time', 'month')->where($wt)->cache(30)->sum("balance");
	   	$this->assign('pts',$pts);
	   	$this->assign('month_pts',$month_pts);
	   	$this->assign('today_pts',$today_pts);
		   
	   	$logs=db('log_paylog_copy')->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_logs=db("log_paylog_copy")->whereTime('add_time', 'week')->cache(30)->sum("balance");
	   	$month_logs=db("log_paylog_copy")->whereTime('add_time', 'month')->cache(30)->sum("balance");
	   	$this->assign("logs",$logs);
	   	$this->assign("today_logs",$today_logs);
	   	$this->assign("week_logs",$week_logs);
	   	$this->assign("month_logs",$month_logs);
		   
	   	$counts=db('log_paylog_copy')->cache(30)->count();
	   	$today_counts=db("log_paylog_copy")->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog_copy")->whereTime('add_time', 'week')->cache(30)->count();
	   	$month_counts=db("log_paylog_copy")->whereTime('add_time', 'month')->cache(30)->count();
	   	$this->assign("counts",$counts);
	   	$this->assign("today_counts",$today_counts);
	   	$this->assign("week_counts",$week_counts);
	   	$this->assign("month_counts",$month_counts);
		   
	   	$this->assign("users",$users);
	   	$this->assign("agents",$agents);
	   	$this->assign("today_users",$today_users);
	   	$this->assign("today_agents",$today_agents);
	   	$this->assign("week_users",$week_users);
	   	$this->assign("week_agents",$week_agents);
	   	$this->assign("month_users",$month_users);
	   	$this->assign("month_agents",$month_agents);
        return  $this->fetch();
    }
	
	//发送短信
	function test_sms(){
		
		//获取对应的短信模板
		$template = db('sms_template') ->where('id',9)->find();
		//短信模板所需参数
		$msg['name'] = 'sdfsd';
		
		//发送短信
		$msg = send_sms('15343353867', $template['tid'], json_encode($msg), $template['sign_name']);
	}
	
	
	//短信验证码
	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	function get_code($mobile, $template_no){
		// 获取短信模板
		$template = db('sms_template') -> find($template_no);
		// 如果是验证码类型，则生成6位验证码
		if($template['type'] == 1){
			$code = rand(100000, 999999);
			$template['params'] = str_replace('${code}', $code, $template['params']);
			$data['code'] = $code;
		}
		$msg = send_sms($mobile, $template['tid'], htmlspecialchars_decode($template['params']), $template['sign_name']);
		$data['mobile'] = $mobile;
		$data['title'] = $template['title'];
		$data['add_time'] = now_time();
		if(isset($msg->result)) {
			$data['message'] = '发送成功';
			db('sms_code')->insert($data);
			return $this->toSuccess('发送成功');
		}else{
			$data['result'] = 0;
			$data['message'] = '发送失败:'.$msg->sub_msg;
			db('sms_code')->insert($data);
			if($msg->sub_code == "isv.BUSINESS_LIMIT_CONTROL"){
				$err = "超过发送次数，请稍后再试";
			}else{
				$err = "发送失败";
			}
			return $this->toError(408, $err);
		}
	}
	
	
	
	//地图定位
	public function position(){

		$other_config=db('tg_admin_system')->where('name','other_config')->find();	
		
		$config_info=unserialize($other_config['value']);
		
		$this->assign('key',$config_info['lbs_key']);
        return  $this->fetch();
    }
	
	//图片上传样例
	public function uploading_test(){
    	
        return  $this->fetch();
    }
	
	//富文本编辑器
	public function wang_editor(){
		if(request()->isAjax()){
			$data = input('post.');
			$ret = db('sys_helps')->insert($data);
		}
		$data =  db('sys_helps')->where('id',13)->find();
		$data['content'] = html_entity_decode($data['content']);
		$this->assign('data',$data);
		return  $this->fetch();
	}
	
	
	
	
	
    
    public function adminshow(){
		$admin_id = session('admin_id');
		$data=Db::name('tg_auth_user')->find();
    	$this->assign('data',$data);
        return  $this->fetch();
    }
    
    
    public function log(){
        $admin_id = session('admin_id');
        $id=Db::name('tg_auth_group_access')->where('uid',$admin_id)->field('group_id')->find();
		$role = Db::name('tg_auth_group')->field('id')->where('id',$id['group_id'])->find();
		$where=[];
		if($role['id']!=1){
			$where['admin_name']=session('admin_name');
		}
        $lists=Db::name('tg_admin_log')->where($where)->order('add_time DESC')->paginate(8);
        $this->assign('list',$lists);
        return  $this->fetch();
    }
    //删除log
    public function logdel(){
        $data['id']=input('id');
	       $result =Db::name('tg_admin_log')->where('id', $data['id'])->delete();
	        if($result){
				 return  $this->success("成功","log",2);
	       }else{
	       		return $this->error("失败");
	       }
        return  $this->fetch();
    }
    
    
   public function config(){
   	$list=Db::name('tg_admin_system')->select();	
    	for($i=0;$i<count($list);$i++){
    		$value=unserialize($list[$i]['value']);
    		$name[$i]=$list[$i]['name'];
    		$this->assign('config'.$i,$value);
    	}
    return $this->fetch('config',['name'=>$name]);
    
   }
   
   public function save()
    {
    	$param=input('post.');
    	if(in_array('site_config',$param)){
    		$where['name']=$param['site_config'];
    	}
    	if(in_array('sms_config',$param)){
    		$where['name']=$param['sms_config'];
    	}
    	if(in_array('wechat_config',$param)){
    		$where['name']=$param['wechat_config'];
    	}
    	if(in_array('payment_config',$param)){
    		$where['name']=$param['payment_config'];
    	}
    	if(in_array('three_config',$param)){
    		$where['name']=$param['three_config'];
    	}
		if(in_array('other_config',$param)){
    		$where['name']=$param['other_config'];
    	}
		if(in_array('fx_config',$param)){
    		$where['name']=$param['fx_config'];
    	}
    	$value['value']=serialize($param);
    	$list=Db::name('tg_admin_system')->where($where)->update($value);
    	$this->success('保存成功' , url('config'));
    }
	
	
	
	//事务处理，需把表引擎类型改为innodb
	function test_db(){
		echo $_SERVER['REQUEST_URI'];
		$is_success = false;
		// 启动事务
		Db::startTrans();
		try{
			
			$res1 = db('test_db')->where('id',1032)->update(['code' => 123456]);
			$data = [
			'title' 		=> 'bar', 
			'mobile' 		=> 'foo',
			'code' 			=> 'foo',
			'message' 		=> 'foo',
			'add_time' 		=> 'foo',
			'aaa' 		=> 'foo',
			'update_time'	=>'foo'
			];
			$res2 = db('test_db')->insert($data);
		   	
		   	
			if($res1 && $res2){
				$is_success = true;
			}
		   
		} catch (\Exception $e) {
			echo '数据异常';
		}
		dump($is_success);
		if($is_success){
			 // 提交事务
		    Db::commit();   
		}else{
			 // 回滚事务
		    Db::rollback();
			echo '数据异常';
		}
	}
	
	
}
